﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Autofac;
using Autofac.Integration.Mvc;

namespace PaperWorld.Web
{
    public static class Bootstrapper
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // 路由名称
                "{controller}/{action}/{id}", // 带有参数的 URL
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // 参数默认值
            );

        }

        public static void RegisterObjects()
        {
            var builder = new ContainerBuilder();

            //注册控制器
            builder.RegisterControllers(typeof(PaperWorld.Web.Controllers.ControllerBase).Assembly)
                .InstancePerHttpRequest();

            builder.RegisterAssemblyTypes((typeof(PaperWorld.Repository.UserRepository).Assembly))
                .AsImplementedInterfaces();

            builder.RegisterAssemblyTypes(typeof(PaperWorld.Service.UserService).Assembly)
                .AsImplementedInterfaces();

            builder.RegisterType<PaperWorld.ORM.DataContext>()
                .As<PaperWorld.ORM.IDataContext>();

            var container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }

        public static void Run()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterObjects();

            RegisterGlobalFilters(GlobalFilters.Filters);

            RegisterRoutes(RouteTable.Routes);

        }
    }
}